<script setup lang="ts">
import printModal from '@/components/business/print-modal/index.vue'
import { getLodop } from '@/lib/lodop/LodopFuncs'
import { taskApi } from '@/api/business/logistics/delivery-api'
import dayjs from 'dayjs'
import { ref , nextTick} from 'vue'
import { message } from 'ant-design-vue'
import { errorSentry } from '@/lib/error-sentry'
import { useUserStore } from '@/store/modules/user-store'
import { useLoadingStore } from '@/store/modules/loading-store'
import { printSettingsConfig } from '@/store/modules/printSettings'
import { useEnums } from '@/hooks/plugins/useEnums'
const { getDescByValue } = useEnums()
const loadingStore = useLoadingStore()
const emit = defineEmits(['close', 'getList'])
const userInfo = useUserStore().getUserInfo

const open = ref<boolean>(false)

const enum GoodsType {
  '销' = 1,
  '赠',
  '退',
  '换'
}
enum OrderType {
  '销售' = 1,
  '退货' = 2,
  '换货' = 3,
  '订货' = 4,
  '订退' = 5
}
const visible = ref(false)
// 详情
const options = ref([])

defineExpose({
  showDrawer
})
const orderId = ref<string>('')
const printLog = ref([])
const driver = ref({})
async function showDrawer(item, val) {
  try {
    loadingStore.show()
    orderId.value = item.id
    const res = await taskApi.detailLoad({ id: item.id })
    printLog.value = res.data.printLog
    driver.value = res.data.driver

    let filteredOptions = res.data.data.map((row) => {
      return {
        ...row,
        creator: item.creator
      }
    })

    if (val === '1') {
      // 当 val 为 1 时，过滤数据
      filteredOptions = filteredOptions.filter((option) => {
        // 示例过滤逻辑：只保留订单类型为 1, 3, 4 的数据
        return [1, 3, 4].includes(option.order_type)
      })
    } else if (val === '2') {
      // 当 val 为 2 时，过滤数据
      filteredOptions = filteredOptions.filter((option) => {
        // 示例过滤逻辑：只保留订单类型为 2, 5 的数据
        return [2, 5].includes(option.order_type)
      })
    }

    options.value = filteredOptions
    if (options.value.length == 0) {
      message.error('这条装车单没有该类型的订单')
    } else {
      visible.value = true
    }
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  } finally {
    loadingStore.hide()
  }
}
function onClose() {
  visible.value = false
}

const loading = ref(false)

const usePrint = () => {
  const onPrint = async (data?: any[]) => {
    loading.value = true
    const list = data.length ? data : options?.value

try {
    const valData = await taskApi.detailLoad({ id: orderId.value, is_print: true })
   printLog.value = valData.data.printLog 
  } catch (error) {
    console.error('更新打印次数失败', error)
    loading.value = false
    return
  }

  await nextTick()

    const LODOP = getLodop()
    if (!LODOP) {
      open.value = true
      loading.value = false
      return
    }
    LODOP.PRINT_INITA(0, '0mm', '241mm', '93mm', '配送单')
    LODOP.SET_PRINT_PAGESIZE(1, '215.9mm', '93mm', '配送单')
    LODOP.SET_PRINT_STYLEA(0, 'TableRowThickNess', '12pt')

    for (let i = 0; i < list.length; i++) {
      const p_dom = document.getElementById(list[i].id)
      // LODOP.ADD_PRINT_HTM(10, '3%', '94%', '100%', p_dom?.outerHTML)
      LODOP.ADD_PRINT_TABLE(20, '3%', '94%', '100%', p_dom?.outerHTML)
      LODOP.ADD_PRINT_TEXT(30, '3%', 196, 20, '县链云仓')
      LODOP.SET_PRINT_STYLEA(0, 'ItemType', 0)
      LODOP.NewPageA()
    }
    
    LODOP.PREVIEW()
    loading.value = false
  }
  return {
    onPrint
  }
}
const { onPrint } = usePrint()
const handleModalClose = () => {
  open.value = false
}
const router = useRouter()
function openNewTab(data) {
  window.open(router.resolve({ path: '/print' }).href + `?order=${data.id}&driver`, '_blank')
}
const getItemOrderTypeText = (orderType) => {
  switch (orderType) {
    case 1:
      return '访销订单'
    case 3:
      return '换货订单'
    case 4:
      return '订货订单'
    case 5:
      return '订退订单'
    default:
      return '退货订单'
  }
}
</script>

<template>
  <printModal :open="open" @cancel="handleModalClose" />
  <a-drawer title="配送单打印" :open="visible" @close="onClose">
    <template #closeIcon>
      <close @on-close="onClose" />
    </template>
    <div class="relative" v-for="(item, index) in options" :key="item.id">
      <div>
        <a-button type="primary" @click="() => onPrint([options[index]])">补单打印</a-button>
        <a-button class="smart-margin-left10" type="primary" @click="openNewTab(item)">自定义打印</a-button>
      </div>

      <table :id="item.id" border="0" center cellSpacing="0" cellPadding="1" width="100%" style="border-collapse: collapse; font-size: 11pt">
        <tbody>
        <tr>
    <td colspan="10">
              <div style="line-height: 30px; text-align: center; font-size: 16pt; font-weight: 700">{{ item?.dealer?.name }} {{ getItemOrderTypeText(item.order_type) }} </div>
              <font style="line-height: 30px;position: absolute; right: 0; top: 0">
                <span>{{ index + 1 }}</span>
                <span>-</span>
                <span>{{options.length}}</span>
              </font>
            </td>
  </tr>
        </tbody>
        <tbody>
          <tr>
            <td colspan="10" v-if="printSettingsConfig.Dengzhou == userInfo.company_id"
              >客户:{{ item?.store?.store_name }}&nbsp;&nbsp;&nbsp;&nbsp; <span>出:{{ item?.warehouse?.name }}({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', item?.warehouse?.attribute_type) }})&nbsp;&nbsp;&nbsp;&nbsp;入:{{ driver?.name }}({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', item?.warehouse?.attribute_type) }})</span>&nbsp;&nbsp;打印次数:{{ printLog?.print_count || 0 }}&nbsp;&nbsp;&nbsp;&nbsp;打印:{{ dayjs().format('YYYY-MM-DD HH:mm:ss') }}&nbsp;&nbsp;&nbsp;&nbsp;单号:{{ item.no }}</td
            >
            <td colspan="10" v-else
              >客户名称:{{ item?.store?.store_name }}&nbsp;&nbsp;&nbsp;&nbsp;<span v-if="item.order_type === 1">出库仓库:{{ item?.warehouse?.name }}({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', item?.warehouse?.attribute_type) }})</span>
              <span v-else-if="item.order_type === 2">入库仓库:{{ item?.warehouse?.name }}({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', item?.warehouse?.attribute_type) }})</span>
              <span v-else-if="item.order_type === 3">出库仓库:{{ item?.warehouse?.name }}({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', item?.warehouse?.attribute_type) }})&nbsp;&nbsp;&nbsp;&nbsp;退回仓库:{{ item?.returnWarehouse?.name }}({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', item?.warehouse?.attribute_type) }})</span>&nbsp;&nbsp;业务员:{{ item?.salesman?.rename }}&nbsp;&nbsp;业务员手机号:{{ item?.salesman?.phone }}&nbsp;&nbsp;&nbsp;&nbsp;订单金额:{{ item?.discounted_amount }}元&nbsp;&nbsp;&nbsp;&nbsp;订单类型:{{ OrderType[item.order_type] }}&nbsp;&nbsp;&nbsp;&nbsp;下单日期:{{ item.create_time }}&nbsp;&nbsp;&nbsp;&nbsp;打印次数:{{ printLog?.print_count || 0 }}&nbsp;&nbsp;&nbsp;&nbsp;打印日期:{{ dayjs().format('YYYY-MM-DD HH:mm:ss') }}&nbsp;&nbsp;&nbsp;&nbsp;单据编号:{{ item.no }}</td
            >
          </tr>
          <tr v-if="printSettingsConfig.Dengzhou == userInfo.company_id">
            <td width="3%" style="border: 1pt solid #000">
              <div align="center"><b></b></div>
            </td>
            <td style="border: 1pt solid #000">
              <div align="center"><b>商品名称</b></div>
            </td>
            <td width="12%" style="border: 1pt solid #000">
              <div align="center"><b>箱码</b></div>
            </td>
            <td width="12%" style="border: 1pt solid #000">
              <div align="center"><b>瓶码</b></div>
            </td>
            <td width="7%" style="border: 1pt solid #000">
              <div align="center"><b>数量</b></div>
            </td>
            <td width="7%" style="border: 1pt solid #000">
              <div align="center"><b>单价</b></div>
            </td>
            <td width="7%" style="border: 1pt solid #000">
              <div align="center"><b>小计</b></div>
            </td>
            <td width="7%" style="border: 1pt solid #000">
              <div align="center"><b>属性</b></div>
            </td>
            <td width="10%" style="border: 1pt solid #000">
              <div align="center"><b>备注</b></div>
            </td>
          </tr>
          <tr v-else>
            <td width="7%" style="border: 1pt solid #000">
              <div align="center"><b></b></div>
            </td>
            <td style="border: 1pt solid #000">
              <div align="center"><b>商品名称</b></div>
            </td>
            <td width="10%" style="border: 1pt solid #000">
              <div align="center"><b>外箱条形码</b></div>
            </td>
            <td width="10%" style="border: 1pt solid #000">
              <div align="center"><b>瓶装条形码</b></div>
            </td>
            <td width="5%" style="border: 1pt solid #000">
              <div align="center"><b>单位</b></div>
            </td>
            <td width="7%" style="border: 1pt solid #000">
              <div align="center"><b>数量</b></div>
            </td>
            <td width="7%" style="border: 1pt solid #000">
              <div align="center"><b>单价</b></div>
            </td>
            <td width="7%" style="border: 1pt solid #000">
              <div align="center"><b>小计</b></div>
            </td>
            <td width="10%" style="border: 1pt solid #000">
              <div align="center"><b>生产日期</b></div>
            </td>
            <td width="7%" style="border: 1pt solid #000">
              <div align="center"><b>保质期</b></div>
            </td>
            <td width="7%" style="border: 1pt solid #000">
              <div align="center"><b>备注</b></div>
            </td>
          </tr>
          <tr v-for="(itemDetail, index) in item.detail" :key="itemDetail.id" v-if="printSettingsConfig.Dengzhou == userInfo.company_id">
            <td style="border: 1pt solid #000; text-align: center">{{ index + 1 }}</td>
            <td style="border: 1pt solid #000; text-align: center">{{ itemDetail?.goods?.goods_name }}</td>
            <td style="border: 1pt solid #000; text-align: center">{{ itemDetail.goods?.spec.find((item) => item.unit_type === 3)?.barcode }}</td>
            <td style="border: 1pt solid #000; text-align: center">{{ itemDetail.goods?.spec.find((item) => item.unit_type === 1)?.barcode }}</td>
            <td style="border: 1pt solid #000; text-align: center">{{ itemDetail.num }}{{ itemDetail?.spec?.unit_name }}</td>
            <td style="border: 1pt solid #000; text-align: center">{{ Number(itemDetail.real_price).toFixed(2) }}</td>
            <td style="border: 1pt solid #000; text-align: center">{{ itemDetail.total_price }}</td>
            <td style="border: 1pt solid #000; text-align: center">{{ GoodsType[itemDetail?.type] }}</td>
            <td style="border: 1pt solid #000; text-align: center">{{ itemDetail.remark }}</td>
          </tr>
          <tr v-for="(itemDetail, index) in item.detail" :key="itemDetail.id" v-else>
            <td style="border: 1pt solid #000; text-align: center">{{ index + 1 }}</td>
            <td style="border: 1pt solid #000; text-align: center">{{ itemDetail?.goods?.goods_name }}</td>
            <td style="border: 1pt solid #000; text-align: center">{{ itemDetail.goods?.spec.find((item) => item.unit_type === 3)?.barcode }}</td>
            <td style="border: 1pt solid #000; text-align: center">{{ itemDetail.goods?.spec.find((item) => item.unit_type === 1)?.barcode }}</td>
            <td style="border: 1pt solid #000; text-align: center">{{ itemDetail?.spec?.unit_name }}</td>
            <td style="border: 1pt solid #000; text-align: center">{{ itemDetail.num }}{{ itemDetail?.spec?.unit_name }}</td>
            <td style="border: 1pt solid #000; text-align: center">{{ Number(itemDetail.real_price).toFixed(2) }}</td>
            <td style="border: 1pt solid #000; text-align: center">{{ itemDetail.total_price }}</td>
            <td style="border: 1pt solid #000; text-align: center">{{ dayjs(itemDetail?.batch_info?.batch_time).format('YYYY-MM-DD') || '' }}</td>
            <td style="border: 1pt solid #000; text-align: center">{{ itemDetail?.goods?.shelf_life_day || '' }}天</td>
            <td style="border: 1pt solid #000; text-align: center">{{ itemDetail.remark }}</td>
          </tr>
          <tr v-if="printSettingsConfig.Dengzhou == userInfo.company_id">
            <td style="border: 1pt solid #000; text-align: center">总</td>
            <td style="border: 1pt solid #000">&nbsp;</td>
            <td style="border: 1pt solid #000">&nbsp;</td>
            <td style="border: 1pt solid #000">&nbsp;</td>
            <td style="border: 1pt solid #000; text-align: center">{{ item.detail.reduce((prev, itemDetail) => prev + itemDetail.num, 0) }}</td>
            <td colspan="4" style="border: 1pt solid #000; text-align: center">
              <span v-if="item.detail.reduce((prev, itemDetail) => prev + Number(itemDetail.total_price), 0).toFixed(2) === Number(item.discounted_amount).toFixed(2)">订单金额：{{ item.detail.reduce((prev, itemDetail) => prev + Number(itemDetail.total_price), 0).toFixed(2) }}元</span>
              <span v-else>原单价：{{ item.detail.reduce((prev, itemDetail) => prev + Number(itemDetail.total_price), 0).toFixed(2) }}元 优惠后：{{ item.discounted_amount }}元</span>
            </td>
          </tr>
          <tr v-else>
            <td style="border: 1pt solid #000; text-align: center">总计</td>
            <td style="border: 1pt solid #000">&nbsp;</td>
            <td style="border: 1pt solid #000">&nbsp;</td>
            <td style="border: 1pt solid #000">&nbsp;</td>
            <td style="border: 1pt solid #000">&nbsp;</td>
            <td style="border: 1pt solid #000; text-align: center">{{ item.detail.reduce((prev, itemDetail) => prev + itemDetail.num, 0) }}</td>
            <td colspan="4" style="border: 1pt solid #000; text-align: center">
              <span v-if="item.detail.reduce((prev, itemDetail) => prev + Number(itemDetail.total_price), 0).toFixed(2) === Number(item.discounted_amount).toFixed(2)">订单金额：{{ item.detail.reduce((prev, itemDetail) => prev + Number(itemDetail.total_price), 0).toFixed(2) }}元</span>
              <span v-else>原单价：{{ item.detail.reduce((prev, itemDetail) => prev + Number(itemDetail.total_price), 0).toFixed(2) }}元 优惠后：{{ item.discounted_amount }}元</span>
            </td>
            <td style="border: 1pt solid #000">&nbsp;</td>
          </tr>
          <tr v-if="printSettingsConfig.Dengzhou == userInfo.company_id">
            <td colspan="10">
              制单:{{ item?.salesman?.rename }}&nbsp;&nbsp;&nbsp;&nbsp;电话:{{ item?.salesman?.phone }}&nbsp;&nbsp;&nbsp;&nbsp; <span style="font-weight: 700">备注:{{ item.remark }}</span>
            </td>
          </tr>
          <tr v-else>
            <td colspan="10">
              <span style="font-weight: 700">备注:{{ item.remark }}</span>
            </td>
          </tr>
          <tr v-if="printSettingsConfig.Dengzhou == userInfo.company_id">
            <td colspan="10"> 门店地址:{{ item?.store?.address }}&nbsp;&nbsp; 门店联系人:{{ item?.store?.contacts }}&nbsp;&nbsp; 联系人电话:{{ item?.store?.phone }}&nbsp; </td>
          </tr>
          <tr v-else>
            <td colspan="10"> 门店地址:{{ item?.store?.address }}&nbsp;&nbsp; 门店联系人:{{ item?.store?.contacts }}&nbsp;&nbsp; 联系人电话:{{ item?.store?.phone }}&nbsp; 制单员:{{ userInfo?.username ?? userInfo.phone }}&nbsp;&nbsp;&nbsp;&nbsp; </td>
          </tr>
          <tr v-if="printSettingsConfig.Dengzhou == userInfo.company_id">
            <td colspan="10" style="font-weight: 500; font-size: 12px">声明：1. 本单据仅确认本次配送产品、数量及货值,个人行为与县链云仓平台无关，责任自负；2.非平台授权行为,平台不担责,单据仅核实本次配送的产品、数量、货值的确认签字:</td>
          </tr>
          <tr v-else>
            <td colspan="5">签收签字:</td>
          </tr>
          <tr v-if="printSettingsConfig.Dengzhou == userInfo.company_id">
            <td colspan="5"></td>
          </tr>
          <tr v-else>
            <td colspan="10" style="font-weight: 500; font-size: 12px">声明：请店方不要接受业务/司机个人的欠条、收据等行为，如有发生纯属店方与业务/司机的个人责任，与我司无关，（交纳预收款请店方提前核实后再交纳）。我司对业务/司机个人所打欠条、收据等概不负责！</td>
          </tr>
        </tbody>
      </table>
    </div>
    <template #footer>
      <div class="flex justify-end">
        <a-button type="default" @click="onClose">关闭</a-button>
        <a-button type="primary" @click="onPrint" :loading="loading" style="margin: 0 8px">打印</a-button>
      </div>
    </template>
  </a-drawer>
</template>
